package stbm.gui;

import java.awt.*;

import javax.swing.*;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

//import GameInitPanel.DifficultyListener;

import java.awt.event.*;

import stbm.guihelpers.*;
import stbm.objects.*;

import java.util.LinkedList;

/**
 * The class representing the Game screen
 * 
 * @author Nisha Lad
 * @author Nirav
 * 
 */

/**
 * Creates a new TradePanel
 */
public class TradePanel extends BasicPanel {

	private double cartPrice;

	private double sellingPrice;

	private static boolean buySomething = false;

	JLabel cartPriceLabel;

	JLabel cash;

	LinkedList<TradeGood> cart;

	LinkedList<TradeGood> itemsToSell;

	JLabel noSellItemsLabel;

	JButton backButton;

	JPanel sellingPanel;

	// ButtonGroup buyingItems = new ButtonGroup();

	GridBagConstraints sellingPanelConstraints;

	LinkedList<JRadioButton> buyingCheckBoxes;

	/**
	 * Creates a new TradePanel with the supplied gameManager
	 * 
	 * @param gameManager
	 */
	public TradePanel(GameManager gameManager) {

		super(gameManager);

	}

	public void clear() {

		this.removeAll();

	}

	/**
	 * Initializes the TradePanel
	 */
	public void build() {

		System.out.println("Current Cargo: " + gameManager.ship.getCargo());
		buyingCheckBoxes = new LinkedList<JRadioButton>();
		this.setBackground(Color.BLACK);
		this.setLayout(new GridBagLayout());
		GridBagConstraints mainPanelConstraints = new GridBagConstraints();
		this.cartPrice = 0.0;
		this.sellingPrice = 0;
		cart = new LinkedList<TradeGood>();
		itemsToSell = new LinkedList<TradeGood>();

		mainPanelConstraints.gridx = 0;
		mainPanelConstraints.gridy = 0;
		JLabel label = new JLabel("<html><h1>Welcome to the "
				+ gameManager.universe.curPlanet.name
				+ " Trading Dock!</h1></html>");
		label.setForeground(Color.YELLOW);
		this.add(label, mainPanelConstraints);

		mainPanelConstraints.gridy++;
		this.cash = new JLabel("<html><h2>Cash: $"
				+ gameManager.player.getCredits() + "</h2></html>");
		cash.setForeground(Color.YELLOW);

		this.add(cash, mainPanelConstraints);

		mainPanelConstraints.gridy++;
		this.cartPriceLabel = new JLabel("<html><h3>Cart: $0</h3><html>");
		cartPriceLabel.setForeground(Color.WHITE);
		this.add(cartPriceLabel, mainPanelConstraints);

		JPanel buyingPanel = new JPanel();
		buyingPanel.setLayout(new GridBagLayout());

		GridBagConstraints buyingPanelConstraints = new GridBagConstraints();
		buyingPanelConstraints.gridx = 0;
		buyingPanelConstraints.gridy = 0;
		/**
		 * Prints out the items available for buying
		 */
		LinkedList<TradeGood> tgs = gameManager.universe.curPlanet.store.tg;

		for (int i = 0; i < tgs.size(); i++) {

			JRadioButton buyingItemButton = new JRadioButton(tgs.get(i)
					.toString());
			// buyingItems.add(buyingItemButton);
			buyingCheckBoxes.add(buyingItemButton);
			buyingItemButton
					.addActionListener(new BuyItemsListener(tgs.get(i)));
			buyingPanelConstraints.gridy = i;
			buyingPanel.add(buyingItemButton, buyingPanelConstraints);

		}

		buyingPanelConstraints.gridy++;
		JButton buyButton = new JButton("Buy");
		buyingPanel.add(buyButton, buyingPanelConstraints);
		buyButton.addActionListener(new BuyListener());

		// buyingPanelConstraints.gridy++;

		this.sellingPanel = new JPanel();
		sellingPanel.setPreferredSize(new Dimension(200, 200));

		JButton sellButton = new JButton("Sell");
		sellButton.addActionListener(new SellListener());

		sellingPanel.setLayout(new GridBagLayout());

		this.sellingPanelConstraints = new GridBagConstraints();
		sellingPanelConstraints.gridx = 0;
		sellingPanelConstraints.gridy = 0;
		// int constraintVal = 0;

		if (gameManager.ship.getCargoCount() != 0) {

			sellingPanel.add(new JLabel("Items to sell: "),
					sellingPanelConstraints);
			for (TradeGood item : gameManager.ship.getCargo()) {

				JRadioButton sellingItemButton = new JRadioButton(
						item.toString());
				sellingPanelConstraints.gridy++;
				sellingPanel.add(sellingItemButton, sellingPanelConstraints);
				sellingItemButton
						.addActionListener(new SellItemsListener(item));
				if (item == gameManager.ship.getCargo().getLast()) {
					sellingPanelConstraints.gridy++;
					sellingPanel.add(sellButton, sellingPanelConstraints);
				}

			}
		} else {
			noSellItemsLabel = new JLabel("You have no items to sell");
			sellingPanel.add(noSellItemsLabel, sellingPanelConstraints);
		}

		JTabbedPane tabbedPane = new JTabbedPane();

		buyingPanel.setPreferredSize(new Dimension(200, 200));
		tabbedPane.add("Buy", buyingPanel);

		tabbedPane.add("Sell", sellingPanel);

		mainPanelConstraints.gridy += 2;
		this.add(tabbedPane, mainPanelConstraints);

		mainPanelConstraints.gridy++;

		JButton backButton = new JButton("Go Back");
		backButton.addActionListener(new BackListener());

		this.add(backButton, mainPanelConstraints);

	}

	public void resetBuyingCartVisually() {

		cart.clear();
		for (JRadioButton button : buyingCheckBoxes) {
			button.setSelected(false);
		}
		cartPrice = 0.0;
		cartPriceLabel
				.setText("<html><h3>Cart: $" + cartPrice + "</h3></html>");

	}

	public void refreshSellingCartVisually() {

		sellingPanel.removeAll();
		itemsToSell.clear();
		if (gameManager.ship.getCargoCount() != 0) {

			sellingPanelConstraints.gridy = 0;
			sellingPanel.add(new JLabel("Items to sell: "),
					sellingPanelConstraints);
			for (TradeGood item : gameManager.ship.getCargo()) {

				JRadioButton sellingItemButton = new JRadioButton(
						item.toString());
				sellingPanelConstraints.gridy++;
				sellingPanel.add(sellingItemButton, sellingPanelConstraints);
				if (item == gameManager.ship.getCargo().getLast()) {
					JButton sellButton = new JButton("Sell");
					sellButton.addActionListener(new SellListener());
					sellingPanelConstraints.gridy++;
					sellingPanel.add(sellButton, sellingPanelConstraints);
				}

			}
		} else {
			sellingPanelConstraints.gridy = 0;
			noSellItemsLabel = new JLabel("You have no items to sell");
			sellingPanel.add(noSellItemsLabel, sellingPanelConstraints);
		}
		sellingPanel.validate();
		sellingPanel.repaint();

	}

	// ========ActionListeners=========

	/*
	 * ActionListener for when the user selects a trade item
	 */
	public class BuyItemsListener implements ActionListener {

		public TradeGood tg;

		public BuyItemsListener(TradeGood tg) {

			this.tg = tg;

		}

		public void actionPerformed(ActionEvent e) {
			// JRadioButton source = (JRadioButton) e.getSource();

			// LinkedList<TradeGood> tgs =
			// gameManager.universe.curPlanet.store.tg;
			// String itemName = source.getText();

			// Add to cart, update cart price, update cart price label

			if (cart.contains(tg)) {
				cartPrice -= tg
						.getRealPrice(gameManager.universe.curPlanet.salesTax);
				cart.remove(tg);
			} else {
				if (Validation.enoughItemsAvailable(tg)) {
					cartPrice += tg
							.getRealPrice(gameManager.universe.curPlanet.salesTax);
					cart.add(tg);
				} else {
					JOptionPane.showMessageDialog(null,
							"We're out of that. Sorry :(", "ERROR",
							JOptionPane.ERROR_MESSAGE);
				}
			}

			// for (int i = 0; i < tgs.size(); i++) {
			//
			// if (tgs.get(i).name == itemName) {
			//
			// if (cart.contains(itemName)) {
			// cartPrice -= tgs.get(i).getRealPrice(
			// gameManager.universe.curPlanet.salesTax);
			// cart.remove(itemName);
			// } else {
			// if (Validation.enoughItemsAvailable(tgs.get(i))) {
			// cartPrice += tgs.get(i).getRealPrice(
			// gameManager.universe.curPlanet.salesTax);
			// cart.add(tgs.get(i).name);
			// } else {
			// JOptionPane.showMessageDialog(null,
			// "We're out of that. Sorry :(", "ERROR",
			// JOptionPane.ERROR_MESSAGE);
			// }
			// }
			//
			// }
			//
			// }
			System.out.println(cartPrice);
			cartPriceLabel.setText("<html><h3>Cart: $" + cartPrice
					+ "</h3></html>");

		}
	}

	/*
	 * ActionListener for the Buy button
	 */
	public class BuyListener implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			// TODO implement

			LinkedList<TradeGood> tgs = gameManager.universe.curPlanet.store.tg;

			if (!Validation.checkCargo(gameManager.ship, cart.size())) {

				JOptionPane.showMessageDialog(null,
						"You have exceeded your cargo space.", "ERROR",
						JOptionPane.ERROR_MESSAGE);

			} else if (!Validation.checkMoney(cartPrice,
					gameManager.player.getCredits())) {
				JOptionPane.showMessageDialog(null,
						"You don't have enough money.", "ERROR",
						JOptionPane.ERROR_MESSAGE);

			} else {

				gameManager.ship.getCargo().addAll(cart);

				for (TradeGood tItem : cart) {

					int ind = tgs.indexOf(tItem);
					tgs.get(ind).quantity--;

				}

				// TEST
				// for (TradeGood tItem : cart) {
				//
				// tItem.quantity = 1;
				//
				// }

				// gameManager.ship.getCargo().addAll(cart);
				//
				// for (TradeGood shipt : gameManager.ship.tg) {
				// shipt.quantity = 1;
				// }

				gameManager.player.setCredits(gameManager.player.getCredits()
						- cartPrice);

				resetBuyingCartVisually();

				System.out.println("You have "
						+ gameManager.player.getCredits() + " credits");
				cash.setText("<html><h2>Cash: $"
						+ gameManager.player.getCredits() + "</h2></html>");

				System.out.println("Cargo: " + gameManager.ship.getCargo());

				/**
				 * Refresh items for selling
				 */
				sellingPanel.removeAll();
				JLabel label = new JLabel(
						"<html>Items for selling:<br/><br/></html>");
				sellingPanel.add(label, sellingPanelConstraints);

				for (TradeGood item : gameManager.ship.getCargo()) {

					JRadioButton sellingItemButton = new JRadioButton(
							item.toString());
					sellingPanelConstraints.gridy++;
					sellingPanel
							.add(sellingItemButton, sellingPanelConstraints);
					sellingItemButton.addActionListener(new SellItemsListener(
							item));
					if (item == gameManager.ship.getCargo().getLast()) {
						JButton sellButton = new JButton("Sell");
						sellButton.addActionListener(new SellListener());
						sellingPanelConstraints.gridy++;
						sellingPanel.add(sellButton, sellingPanelConstraints);
					}

				}

			}

			try {
				gameManager.saveState();
			} catch (ParserConfigurationException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (TransformerException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

		}
	}

	/**
	 * Handles the event when an item to sell is selected
	 * 
	 * @author Nirav
	 * 
	 */
	public class SellItemsListener implements ActionListener {

		public TradeGood tg;

		public SellItemsListener(TradeGood tg) {
			this.tg = tg;
		}

		public void actionPerformed(ActionEvent e) {

			if (itemsToSell.contains(tg)) {
				sellingPrice -= tg
						.getRealPrice(gameManager.universe.curPlanet.salesTax);
				itemsToSell.remove(tg);
			} else {

				sellingPrice += tg
						.getRealPrice(gameManager.universe.curPlanet.salesTax);
				itemsToSell.add(tg);

			}

			System.out.println(sellingPrice);
			cartPriceLabel.setText("<html><h3>Selling items worth $"
					+ sellingPrice + "</h3></html>");

		}
	}

	/*
	 * ActionListener for the Sell button
	 */
	public class SellListener implements ActionListener {

		public void actionPerformed(ActionEvent e) {

			if (!Validation.sellingItemsWithinItemCount(gameManager.ship,
					itemsToSell.size())) {

				JOptionPane.showMessageDialog(null,
						"You have less items than you're trying to sell.",
						"ERROR", JOptionPane.ERROR_MESSAGE);

			} else {

				LinkedList<TradeGood> tgs = gameManager.universe.curPlanet.store.tg;

				for (TradeGood tItem : itemsToSell) {

					int ind = tgs.indexOf(tItem);
					if (ind != -1) {
						tgs.get(ind).quantity++;
					} else {
						tgs.add(tItem);
					}

				}

				for (TradeGood tItem : itemsToSell) {

					gameManager.ship.removeCargo(tItem);

				}

				gameManager.player.setCredits(gameManager.player.getCredits()
						+ sellingPrice);
				cartPriceLabel.setText("<html><h3>Sold Items worth: $"
						+ sellingPrice + "</h3></html>");
				cash.setText("<html><h2>Cash: $"
						+ gameManager.player.getCredits() + "</h2></html>");

				sellingPrice = 0;
				refreshSellingCartVisually();
				System.out.println(gameManager.ship.getCargo());
			}

			try {
				gameManager.saveState();
			} catch (ParserConfigurationException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (TransformerException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

		}
	}

	public class BackListener implements ActionListener {

		public void actionPerformed(ActionEvent e) {

			clear();
			gameManager.switchScreens(GameSpecifics.GAME_SCREEN);

		}

	}

}
